package top.lgd.controller.study;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.lgd.base.LgdConstants;
import top.lgd.base.LgdResult;
import top.lgd.base.LgdTable;
import top.lgd.controller.LgdController;
import top.lgd.pojo.entity.study.Catalog;
import top.lgd.pojo.entity.study.Content;
import top.lgd.pojo.req.study.ContentReq;
import top.lgd.service.study.CatalogService;
import top.lgd.service.study.ContentService;
import top.lgd.utils.DateUtils;
import top.lgd.utils.NumberUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Set;

/**
 * @author YYJ
 * @version 1.0
 * @since 2023/12/19 19:12
 */
@RestController
@RequestMapping("/admin/studyContent")
public class ContentAdminController extends LgdController {

    @Autowired
    private ContentService contentService;

    @Autowired
    private CatalogService catalogService;

    /**
     * 查询学习内容列表
     *
     * @return
     */
    @PostMapping("/queryList")
    public LgdTable<Content> queryList(@RequestBody Content content) {
        Long catalogId = content.getCatalogId();
        content.setCatalogId(null);

        QueryWrapper<Content> queryWrapper = new QueryWrapper(content);
        Set<Long> catalogIds = catalogService.queryDescendantIds(catalogId);
        queryWrapper.eq(LgdConstants.COLUMN_DATA_USER_ID, current().getId())
                .in(CollectionUtil.isNotEmpty(catalogIds), LgdConstants.COLUMN_CATALOG_ID, catalogIds)
                .orderByAsc(LgdConstants.COLUMN_STATUS, LgdConstants.COLUMN_SORT_NUM);
        Page<Content> page = contentService.page(new Page(content.getCurrent(), content.getPageSize()), queryWrapper);
        page.getRecords().forEach(c -> {
            c.setCatalogName(catalogService.queryAllName(c.getCatalogId()));
            c.setCurrentProgress(NumberUtils.div(c.getDoneIndex(), c.getTargetIndex(), 2).multiply(new BigDecimal(100)));
            if (null != c.getStartDate()) {
                LocalDate lastStudyDate = null != c.getEndDate() ? c.getEndDate() : LocalDate.now();
                c.setStudyDays((int) DateUtils.between(c.getStartDate(), lastStudyDate, ChronoUnit.DAYS) + 1);
            }
        });
        return getTable(page);
    }

    /**
     * 添加编辑学习内容
     *
     * @param content 学习内容 对象
     * @return
     */
    @PostMapping("addUpdate")
    public LgdResult<Content> addUpdate(@RequestBody Content content) {
        if (null != content.getId()) {
            UpdateWrapper<Content> updateWrapper = new UpdateWrapper();
            updateWrapper.eq(LgdConstants.COLUMN_ID, content.getId())
                    .eq(LgdConstants.COLUMN_DATA_USER_ID, current().getId());
            contentService.update(content, updateWrapper);
        } else {
            Catalog catalog = catalogService.queryCatalog(content.getCatalogId());
            if (LgdConstants.LONG_ZERO == catalog.getParentid()) {
                content.setRootCatalogId(catalog.getId());
            } else {
                content.setRootCatalogId(Long.parseLong(catalog.getAncestors().split(LgdConstants.ANCESTORS_SPLIT)[1]));
            }
            content.setDataUserId(current().getId());
            contentService.save(content);
        }
        return LgdResult.success(content);
    }

    /**
     * 删除学习内容
     *
     * @param id 学习内容ID
     * @return
     */
    @PostMapping("remove")
    public LgdResult<String> remove(@RequestParam Long id) {
        if (contentService.remove(new QueryWrapper<Content>()
                .eq(LgdConstants.COLUMN_ID, id)
                .eq(LgdConstants.COLUMN_DATA_USER_ID, current().getId()))) {
            return LgdResult.success("删除学习内容成功");
        } else {
            return LgdResult.fail("删除学习内容失败");
        }
    }

    /**
     * 开始学习内容
     *
     * @param id 学习内容ID
     * @return
     */
    @PostMapping("start")
    public LgdResult<String> start(@RequestParam Long id) {
        UpdateWrapper<Content> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set(LgdConstants.COLUMN_START_DATE, LocalDate.now())
                .set(LgdConstants.COLUMN_END_DATE, null)
                .set(LgdConstants.COLUMN_DONE_INDEX, 0)
                // 状态 0-学习中 1-待学习 2-已学习
                .set(LgdConstants.COLUMN_STATUS, "0")
                .eq(LgdConstants.COLUMN_ID, id)
                .eq(LgdConstants.COLUMN_DATA_USER_ID, current().getId());
        if (contentService.update(updateWrapper)) {
            return LgdResult.success("开始学习内容成功");
        } else {
            return LgdResult.fail("开始学习内容失败");
        }
    }

    /**
     * 更新进度
     *
     * @param contentReq 更新进度
     * @return
     */
    @PostMapping("updateProgress")
    public LgdResult<String> updateProgress(@RequestBody ContentReq contentReq) {
        if (contentService.updateProgress(contentReq, "N", current().getId())) {
            return LgdResult.success("更新进度成功");
        } else {
            return LgdResult.fail("更新进度失败");
        }
    }

    /**
     * 更新进度
     *
     * @param contentReq 更新进度
     * @return
     */
    @PostMapping("focusProgress")
    public LgdResult<String> focusProgress(@RequestBody ContentReq contentReq) {
        if (contentService.updateProgress(contentReq, "F", current().getId())) {
            return LgdResult.success("更新进度成功");
        } else {
            return LgdResult.fail("更新进度失败");
        }
    }
}